// ignore_for_file: depend_on_referenced_packages

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/hj_page/mine_business/identity/mine_identity_page.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/widget/common_dialog.dart';

import '../../hj_model/splash/domain_source_model.dart';
import '../../hj_utils/global.dart';
import '../../hj_utils/utils.dart';
import '../../tools_base/net/load_apk/dio_cli.dart';
import '../../tools_base/net/load_apk/dio_slice_downloader.dart';

//升级版本对话框
class UpdateDialog extends StatefulWidget {
  static Future show(CheckVersionInfo phoneBean) async {
    return await Get.dialog(
      UpdateDialog(updateInfo: phoneBean),
      barrierDismissible: false,
    );
  }

  final CheckVersionInfo updateInfo;

  const UpdateDialog({super.key, required this.updateInfo});

  @override
  State<UpdateDialog> createState() => _UpdateDialog();
}

class _UpdateDialog extends State<UpdateDialog> {
  bool isUpdate = false;
  bool isReDownload = false;
  var progress = .0;

  String apkPath = "";

  @override
  void initState() {
    super.initState();
  }

  void _loadApkEvent() async {
    if (progress == 1.0) {
      await installApk();
      return;
    }
    if (isUpdate) {
      return;
    }
    //开始下载
    isUpdate = true;
    String devId = await getDeviceOaid();
    Clipboard.setData(ClipboardData(text: "***" + devId + "^^^"));
    _downloadApp(widget.updateInfo.url ?? "");
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return _buildContent();
  }

  Widget _buildContent() {
    return CommonDialog(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                '系统升级',
                style: TextStyle(
                  color: Colors.white.withOpacity(.9),
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                ),
              ),
              12.sizeBoxH,
              0.5.line,
              12.sizeBoxH,
              Row(
                children: [
                  Text(
                    "更新版本  v ${widget.updateInfo.verName}",
                    style: TextStyle(
                      color: Colors.white.withOpacity(.9),
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
              12.sizeBoxH,
              SizedBox(
                height: 175,
                child: SingleChildScrollView(
                  physics: const ClampingScrollPhysics(),
                  child: Row(
                    children: [
                      Text(
                        widget.updateInfo.description?.replaceAll("|", "\n") ?? "",
                        style: TextStyle(
                          color: Colors.white.withOpacity(.55),
                          fontSize: 12,
                          height: 1.6,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          18.sizeBoxH,
          InkWell(
            onTap: () => Get.to(() => const MineAccountIdentityPage()),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  "保存账号凭证",
                  style: TextStyle(
                    color: Colors.white.withOpacity(.55),
                    fontSize: 14,
                  ),
                ),
                3.sizeBoxW,
                Icon(
                  Icons.arrow_forward_ios_outlined,
                  size: 14,
                  color: Color(0xffDCDCDC),
                )
              ],
            ),
          ),
          18.sizeBoxH,
          if (isUpdate) ...[
            Container(
              padding: EdgeInsets.zero,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: LinearPercentIndicator(
                      lineHeight: 3,
                      percent: progress,
                      barRadius: const Radius.circular(3),
                      animationDuration: 1200,
                      trailing: const SizedBox(),
                      backgroundColor: Color(0xffBEBEBE),
                      progressColor: AppColors.actionRed,
                    ),
                  ),
                  12.sizeBoxH,
                  Text(
                    "${((progress * 100).toInt())}%",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white.withOpacity(.55),
                    ),
                  ),
                ],
              ),
            ),
          ] else
            _buildButtonMenu(),
        ],
      ),
    );
  }

  Widget _buildButtonMenu() {
    if (widget.updateInfo.forcedUpdate == true) {
      return _buildUpdateBtn();
    } else {
      return Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: () => Get.back(),
              child: Container(
                height: 44,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  color: Colors.white.withOpacity(.1),
                ),
                child: Text(
                  "暂不升级",
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Color(0xff989898),
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(child: _buildUpdateBtn()),
        ],
      );
    }
  }

  _buildUpdateBtn() {
    return GestureDetector(
      onTap: () => _loadApkEvent(),
      child: Container(
        height: 44,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: AppColors.actionRed,
          borderRadius: BorderRadius.circular(3),
        ),
        child: const Text(
          "立即升级",
          style: TextStyle(
            fontSize: 14,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  ///下载app
  _downloadApp(String url) async {
    final saveDirectory = path.join((await getExternalStorageDirectory())?.path ?? "", "apk");
    DioSliceRetryDownloader(DioCli(), url, null, saveDirectory, "paofu.apk", onReceiveProgress: (count, total) {
      progress = (count / total);
      setState(() {});
    }, onRetry: (int retryCount) {
      showToast("下载发生错误正在自动重试中...($retryCount)");
    }).download().then((String savePath) async {
      apkPath = savePath;
      await installApk();
    }).catchError((e) {
      showToast("下载发生错误,点击重新进行下载.");
      setState(() {
        isReDownload = true;
        isUpdate = false;
      });
    });
  }

  ///安装apk
  // 安装
  Future<bool> installApk() async {
    //    String savePath = (await getExternalStorageDirectory()).path + "/yinse.apk";
    bool exit = await File(apkPath).exists();
    if (!exit) {
      return Future.value(false);
    }
    String devId = await getDeviceOaid();
    Clipboard.setData(ClipboardData(text: "***" + devId + "^^^"));
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    InstallPlugin.installApk(apkPath, appId: packageInfo.packageName).then((result) {
//      showToast( result);
//      safePopPage(false);
    }).catchError((error) {});
    return Future.value(true);
  }
}
